<?php
/**
 * Created by PhpStorm.
 * User: huawei
 * Date: 2021/8/6
 * Time: 16:41
 */

namespace app\admin\controller;
use think\App;
use app\model\Company as model;

class Company extends Common
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * @return string
     * @throws \think\db\exception\DbException
     */
    public function index(){
        $keyword = $this->request->get("keyword");
        $sel = $this->request->get("sel",false);

        $model = new model();
        if($keyword){
            $where[]=["title_cn"];
            $model = $model->whereOr("title_cn","LIKE","%".$keyword."%")
                ->whereOr("title_other","LIKE","%".$keyword."%");
        }

        $lists = $model->paginate([
            'list_rows'=>15,
            'query'=>[
                'keyword'=>$keyword,
                'sel'=>$sel
            ]
        ],true);

        return $this->view("",[
            "lists"=>$lists,
            "sel"=>$sel,
        ]);
    }
    public function add(){
        return $this->view("company/post",[
            "item"=>null
        ]);
    }

    /**
     * @title 编辑
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(){
        $id = $this->request->get("id");
        $model = new model();
        $item = $model->find($id);
        return $this->view("company/post",["item"=>$item]);
    }

    public function post(){
        if($this->request->isPost()){
            $data = [
              "logo"=>$this->request->post("logo",null),
              "title_cn"=>$this->request->post("title_cn",null),
              "title_other"=>$this->request->post("title_other",null),
              "country"=>$this->request->post("country",null),
              "address"=>$this->request->post("address",null),
              "desc"=>$this->request->post("desc",null),
            ];
            $check = $this->validate($data,[
                'title_cn|名称'=>'require',
            ]);
            if($check){
                return $this->error($check);
            }
            $model = new model();
            $id = $this->request->post("id");
            if($id){
                $model->where("id",$id)->save($data);
            }else{
                $model->save($data);
            }
            return $this->success("保存成功");
        }
    }

    /**
     * @title 删除
     * @return $this
     */
    public function del(){
        $id = $this->request->post("id");
        $model = new model();
        if(is_array($id)){
            $model->whereIn("id",$id)->delete();
        }else{
            $model->where("id",$id)->delete();
        }
        return $this->success("删除成功");
    }
}